// let extend = require( 'lodash/extend' )
import { extend, isJson } from './Tool'

const request = function (option) {
  // 默认配置项
  const _default = {
    // ajax设置
    url: '',
    type: 'POST',
    dataType: 'json',
    data: null, // 传输数据，
    fileData: null,
    timeout: 20,
    success: null,
    error: null
  }

  const _custom = extend(_default, option)

  const paramData = {}

  let url = _custom.url
  if (remote) {
    url = remote.url(url)
  }
  const accessToken = remote && remote.debug() ?
    remote.debugUserId() : $api.getStorage('userId')

  let headers = {
    authorization: accessToken,
    mobile: 'true'
  }

  headers = extend(headers, _custom.headers || {})
  let isBody = false
  let isForm = _custom.type.toLowerCase() === 'post'

  if (headers['Content-Type']) {
    const js = headers['Content-Type'].indexOf('json') !== -1
    const txt = headers['Content-Type'].indexOf('text') !== -1
    if (js || txt) {
      isBody = true
      isForm = false
    }
  }
  if (isBody) {
    paramData.body = _custom.data
  } else if (isForm) {
    paramData.values = _custom.data
  }
  if (_custom.fileData) {
    paramData.files = _custom.fileData
  }
  api.showProgress({
    title: '努力加载中...',
    text: '先喝杯茶...',
    modal: true
  })
  if (remote && remote.debug()) {
    console.log(`param=${JSON.stringify(_custom.data)}`)
  }
  api.ajax({
    url,
    method: _custom.type,
    data: paramData,
    timeout: _custom.timeout,
    headers
  }, (ret, err) => {
    api.hideProgress()
    if (remote && remote.debug()) {
      console.log(`ret=${JSON.stringify(ret)}`)
      console.log(`err=${JSON.stringify(err)}`)
    }
    if (ret) {
      if (ret.status !== 'ok') {
        api.alert({
          msg: ret.message || `${_custom.url}:后台未提供错误信息`,
        })
      } else if (_custom.success) _custom.success(ret)
    } else if (_custom.error) {
      _custom.error(err)
    } else if (err.statusCode === 500) {
      api.alert({
        msg: `${_custom.url}:500:后台未验证传送的数据或其它错误`,
      })
    } else if (remote && remote.debug()) {
      api.alert({
        msg: JSON.stringify(err)
      })
    } else {
      api.alert({
        msg: err.msg || err.body || '系统未捕获到错误信息，请联系管理员'
      })
    }
  })
}

function toQueryPair(key, value) {
  if (typeof value === 'undefined') {
    return key
  }
  return `${key}=${encodeURIComponent(value === null ? '' : String(value))}`
}

function queryStr(obj) {
  let ret = []
  for (let key in obj) {
    key = encodeURIComponent(key)
    const values = obj[key]
    if (values && values.constructor === Array) { // 数组
      const queryValues = []
      for (let i = 0, len = values.length, value; i < len; i++) {
        value = values[i]
        queryValues.push(toQueryPair(key, value))
      }
      ret = ret.concat(queryValues)
    } else { // 字符串
      ret.push(toQueryPair(key, values))
    }
  }
  return ret.join('&')
}

const post = function (url, data, success) {
  if (typeof (data) === 'function') {
    success = data
    data = {}
  }
  request({
    url,
    data,
    success,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    }
  })
}

const postJson = function (url, data, success) {
  if (typeof (data) === 'function') {
    success = data
    data = {}
  }

  request({
    url,
    data,
    success,
    headers: {
      'Content-Type': 'application/json;charset=utf-8'
    }
  })
}

const postText = function (url, data, success) {
  if (typeof (data) === 'function') {
    success = data
    data = ''
  }
  if (isJson(data)) {
    data = JSON.stringify(data)
  }
  request({
    url,
    data,
    success,
    headers: {
      'Content-Type': 'text/plain;charset=utf-8'
    }
  })
}

const get = function (url, data, success) {
  if (typeof (data) === 'function') {
    success = data
    data = {}
  }
  const qrs = queryStr(extend(data, {
    _t: new Date()
      .getTime()
  }))
  request({
    url: `${url}?${qrs}`,
    type: 'get',
    success
  })
}

window.Ajax = {
  request,
  post,
  get,
  postJson,
  postText,
  postForm: post
}

export default {
  request,
  post,
  get,
  postForm: post,
  postJson,
  postText,
  //  pomise,
  queryStr
}
